<template>
  <div>
    <div class="tips_box">
      <p class="tips">
        <span style="margin-right: 20px">{{ "剧目名称：" }}</span>
        <span>{{ operaName }}</span>
      </p>
    </div>
    <div class="table_box_wrapper">
      <div class="title_box" style="margin-top: unset">
        <i class="i"></i>
        <span class="title">腾讯云点播文件列表</span>
        <el-button type="primary" @click="refresh">
          <el-icon style="margin-right: 5px">
            <Refresh />
          </el-icon>
          从腾讯云点播刷新文件列表
        </el-button>
      </div>
      <custom-table
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :typeSelect="true"
        @selectionChange="selectionChange"
        :isPagination="false"
        :maxHeight="300"
        class="table_box"
      >
        <template #status="{ scope }">
          <span :class="[scope.row.status === 'Normal' ? 'green' : 'red']">
            {{ scope.row.status === "Normal" ? "启用" : "禁用" }}
          </span>
        </template>
        <!-- pass：建议通过；review：建议复审；block：建议封禁 -->
        <template #mediaReviewSuggestion="{ scope }">
          <span
            :class="[
              scope.row.mediaReviewSuggestion === 'pass' ? 'green' : 'red',
            ]"
          >
            {{
              scope.row.mediaReviewSuggestion === "pass"
                ? "通过"
                : scope.row.mediaReviewSuggestion === "review"
                ? "复审"
                : "违规"
            }}
          </span>
        </template>
        <template #operator="{ scope }">
          <span class="operationClick" @click="deleteFile(scope.row)">
            删除
          </span>
        </template>
      </custom-table>
      <!-- 没有错误原因显示主小程序 -->
      <template v-if="!reason.length || getReason()">
        <!-- 微信小程序 -->
        <div class="title_box">
          <i class="i"></i>
          <span class="title">同步到各主微信小程序</span>
        </div>
        <custom-table
          :columns="wx_columns"
          :tableData="wx_tableData"
          :isPagination="false"
          :maxHeight="300"
          class="table_box"
        >
          <template #app="{ scope }">
            {{ scope.row.app?.appName }}
          </template>
          <template #uploadedCount="{ scope }">
            <span
              v-if="
                !scope.row?.uploadingCount &&
                !scope.row?.uploadedCount &&
                !scope.row?.uploadFailedCount
              "
            >
              {{ "还未创建同步任务" }}
            </span>
            <template
              v-else-if="scope.row?.uploadedCount !== scope.row?.taskCount"
            >
              <span class="blue">
                {{ `上传中${scope.row?.uploadingCount}个` }}
              </span>
              <span class="green">
                {{ ` / 上传成功${scope.row?.uploadedCount}个` }}
              </span>
              <span class="red">
                {{ ` / 上传失败${scope.row?.uploadFailedCount}个` }}
              </span>
            </template>
            <template v-else>
              <span class="green">
                {{ `上传成功${scope.row?.uploadedCount}个` }}
              </span>
            </template>
          </template>
          <template #operator="{ scope }">
            <span class="operationClick" @click="handdel(scope.row, 'wx')">
              查看任务详情
            </span>
          </template>
        </custom-table>
        <!-- 抖音小程序 -->
        <div class="title_box">
          <i class="i"></i>
          <span class="title">同步到各主抖音小程序</span>
        </div>
        <custom-table
          :columns="dy_columns"
          :tableData="dy_tableData"
          :isPagination="false"
          :maxHeight="300"
          class="table_box"
        >
          <template #app="{ scope }">
            {{ scope.row.app?.appName }}
          </template>
          <template #uploadedCount="{ scope }">
            <span
              v-if="
                !scope.row?.uploadingCount &&
                !scope.row?.uploadedCount &&
                !scope.row?.uploadFailedCount
              "
            >
              {{ "还未创建同步任务" }}
            </span>
            <template
              v-else-if="scope.row?.uploadedCount !== scope.row?.taskCount"
            >
              <span class="blue">
                {{ `上传中${scope.row?.uploadingCount}个` }}
              </span>
              <span class="green">
                {{ `/ 上传成功${scope.row?.uploadedCount}个` }}
              </span>
              <span class="red">
                {{ `/ 上传失败${scope.row?.uploadFailedCount}个` }}
              </span>
            </template>
            <template v-else>
              <span class="green">
                {{ `上传成功${scope.row?.uploadedCount}个` }}
              </span>
            </template>
          </template>
          <template #operator="{ scope }">
            <span class="operationClick" @click="handdel(scope.row, 'dy')">
              查看任务详情
            </span>
          </template>
        </custom-table>
      </template>
    </div>
    <div style="margin-top: 20px" v-if="reason.length && !getReason()">
      <el-alert type="error" show-icon :closable="false" :title="errTitle">
        <span style="font-size: 15px" v-html="errMsg"></span>
      </el-alert>
    </div>

    <div class="footer_box" v-if="!reason.length || getReason()">
      <el-button
        type="primary"
        class="btn"
        @click="syncFile"
        :disabled="!selectionData?.length"
      >
        {{
          `开始同步所选文件（${selectionData?.length}/${tableData?.length}）`
        }}
      </el-button>
    </div>

    <!-- 任务详情 -->
    <taskDetail ref="taskDetailRef" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import {
  mediasList,
  uploadTasksList,
  syncMediasList,
  syncTasks,
  deleteMedias,
} from "@/api/operateCenter/episode/index";
import { Refresh } from "@element-plus/icons-vue";
import type { Action } from "element-plus";
import { useRoute } from "vue-router";
import taskDetail from "./components/taskDetail.vue";
const route = useRoute();
const loading = ref<boolean>(false);
const selectionData = ref<Array<any>>([]);

const tableData = ref<Array<any>>([]);
const wx_tableData = ref<Array<any>>([]);
const dy_tableData = ref<Array<any>>([]);
const reason = ref<Array<any>>([]);
const errTitle = ref<string>("");
const errMsg = ref<string>("");
const operaId = ref(Number(route.query?.id));
const operaName = ref(route.query?.name);

const columns = reactive([
  { prop: "name", label: "文件名", minWidth: 120 },
  { prop: "episode", label: "集数", sortable: true, minWidth: 120 },
  { prop: "status", label: "状态", slotName: "status", minWidth: 120 },
  {
    prop: "mediaReviewSuggestion",
    label: "审核记录",
    slotName: "mediaReviewSuggestion",
    minWidth: 120,
  },
  {
    prop: "size",
    label: "文件大小",
    minWidth: 100,
    formatter: (row: Record<string, any>) => {
      return `${(row.size / (1024 * 1024)).toFixed(3)}MB`;
    },
  },
  { prop: "operator", slotName: "operator", label: "操作", width: 100 },
]);

const wx_columns = reactive([
  { prop: "app", label: "主微信小程序名称", slotName: "app", minWidth: 120 },
  { prop: "taskCount", label: "已创建任务数", minWidth: 120 },
  {
    prop: "uploadedCount",
    label: "媒资同步状态",
    slotName: "uploadedCount",
    minWidth: 220,
  },
  { prop: "operator", slotName: "operator", label: "操作", width: 180 },
]);

const dy_columns = reactive([
  { prop: "app", label: "主抖音小程序名称", slotName: "app", minWidth: 120 },
  { prop: "taskCount", label: "已创建任务数", minWidth: 120 },
  {
    prop: "uploadedCount",
    label: "媒资同步状态",
    slotName: "uploadedCount",
    minWidth: 220,
  },
  { prop: "operator", slotName: "operator", label: "操作", width: 180 },
]);

// 删除文件
const deleteFile = async (row: Record<string, any>) => {
  ElMessageBox.alert(`确定要删除这个文件吗？`, "提醒", {
    confirmButtonText: "确定",
    callback: (action: Action) => {
      if (action == "confirm") {
        deleteMedias(row?.fileId).then(() => {
          ElMessage.success("删除成功");
          getList();
        });
      }
    },
  });
};

// 查看详情
const taskDetailRef = ref();
const handdel = (row: Record<string, any>, str: string) => {
  // if (str === "wx") {
  //   taskDetailRef.value.showDialog(row);
  // } else if (str === "dy") {
  //   taskDetailRef.value.showDialog(row);
  // }
  row.id = operaId.value;
  taskDetailRef.value.showDialog(row);
};

// 刷新云点播文件列表
const refresh = () => {
  syncMediasList(operaId.value).then(() => {
    getList();
  });
};

// 同步小程序
const syncFile = () => {
  let params = {
    operaId: operaId.value, // 剧目id
    // appIds: '',
    vodFileIds: selectionData.value.map((x: Record<string, any>) => {
      return x.fileId;
    }),
  };
  syncTasks(params).then(() => {
    getUploadTasksList(1);
  });
};

// 获取文件列表
const getList = () => {
  loading.value = true;
  mediasList(operaId.value)
    .then((res: Record<string, any>) => {
      tableData.value = res.medias;
      reason.value = res?.reason || [];
      if (reason.value.includes(4)) {
        errMsg.value = `未能从腾讯云点播获取到任何关于此剧目的媒体文件信息<br> 请检查媒体文件是否上传或者相关媒体文件的分类是否设置正确<br>如果你确定已经上传了媒体文件并且分类也设置正确，请点击上面“<b>从腾讯云点播刷新文件列表</b>” 按钮`;
      }
      //  else if (reason.value.includes(1)) {
      //   errTitle.value = "当前有违规文件";
      //   errMsg.value = `当前有视频文件审核“违规”，请登录腾讯云点播查看详细违规内容，呆剪辑重新修改后，重新上传腾讯云点播<br> 如果你已经重新上传，请点击上面的“<b>从腾讯云点播刷新文件列表</b>”，更新文件列表状态`;
      // }
      else if (reason.value.includes(2)) {
        errTitle.value = "";
        errMsg.value = `剧目集数中断，缺少连续的集数`;
      } else if (reason.value.includes(3)) {
        errTitle.value = "";
        errMsg.value = `剧目中存在重复的集数`;
      }
      // 当没有错误原因时调用
      if (!reason.value.length || getReason()) {
        getUploadTasksList();
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

// 当且仅当reason。value长度为1，且数值为1的时候，可以通过媒资同步
const getReason = () => {
  return reason.value.length === 1 && reason.value.some((x) => x === 1);
};

// 获取主小程序列表
const getUploadTasksList = (val = 0) => {
  uploadTasksList(operaId.value).then((res: Record<string, any>) => {
    wx_tableData.value = res?.wxTasks || [];
    dy_tableData.value = res?.dyTasks || [];
    if (val === 1) {
      ElMessage.success("同步成功");
    }
  });
};

// 多选
const selectionChange = (val: Array<any>) => {
  selectionData.value = val;
};

onMounted(() => {
  getList();
});
</script>
<style scoped lang="scss">
.tips_box {
  padding: 15px;
  margin: unset;
  margin-bottom: 12px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .tips {
    margin-bottom: 4px;
    font-size: 18px;
    color: #363636;
  }
}

.table_box_wrapper {
  padding-top: 10px;
  margin-bottom: 12px;
  background-color: #fff;

  .title_box {
    padding-left: 10px;
    margin-top: 20px;

    .i {
      display: inline-block;
      width: 8px;
      height: 16px;
      margin-right: 4px;
      vertical-align: middle;
      background-color: #145eff;
      border-radius: 0 3px 3px 0;
    }

    .title {
      margin-right: 12px;
      font-size: 15px;
      font-weight: bold;
      color: #333;
      vertical-align: middle;
    }
  }

  .table_box {
    :deep(.el-table__inner-wrapper) {
      height: 100% !important;
    }
  }
}

.footer_box {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 9;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 80px;
  background-color: #fff;

  .btn {
    margin-left: 210px;
  }
}
</style>
